<!-- 时间段 -->
<template>
    <bs-dialog title="时间段" :visible="visible" size="default" class="deviceDialog" @opened="initBasicData" :before-close="doCloseEdit">
        <template slot="main">
            <el-form :inline="true" :model="formData" ref="resultDataRef" label-width="110px" size="small" :show-message="false" :hide-required-asterisk="true" :status-icon="false">
                <el-form-item>
                    <el-select v-model="start" :placeholder="$t('请选择开始时间')" size="small" style="width:142px" filterable remote>
                        <template slot="prefix"><i class="el-icon-time" style="padding: 5px;margin-top: 3.5px;" /></template>
                        <el-option v-for="(item, index) in timeSlotArray" :key="index" :label="item.name" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>{{ $t('至') }}</el-form-item>
                <el-form-item>
                    <el-select v-model="end" :placeholder="$t('请选择结束时间')" size="small" style="width:142px" filterable remote>
                        <template slot="prefix"><i class="el-icon-time" style="padding: 5px;margin-top: 3.5px;" /></template>
                        <el-option v-for="(item, index) in endTimeSlotArray" :key="index" :label="item.name" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-slider v-model="brightness" style="width:240px; margin: 0 15px;"></el-slider>
                </el-form-item>
                <el-form-item>
                    <bs-add-button-icon :show-icon="false" @click.native="doAddWeekInfo"></bs-add-button-icon>
                    <bs-delete-button-icon :show-icon="false" @click.native="deleteRow"></bs-delete-button-icon>
                    <bs-clean-button-icon @click.native="deleteAll"></bs-clean-button-icon>
                </el-form-item>
                <el-row>
                    <el-col :span="24">
                        <el-form-item>
                            <el-table ref="table" :data="tableData" style="width: 100%;border:1px solid #e9e9e9;border-bottom:0;" :show-header="false" height="270px" @selection-change="handleSelectionDownloadsChange" @row-click="getCurrentRow">
                                <el-table-column type="selection" width="40px"></el-table-column>
                                <el-table-column prop="timeinfo" width="100px"></el-table-column>
                                <el-table-column prop="weekinfo"></el-table-column>
                            </el-table>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template slot="footer">
            <bs-confirm-button-icon @click.native="doSave"></bs-confirm-button-icon>
            <bs-cancel-button-icon @click.native="doCloseEdit"></bs-cancel-button-icon>
        </template>
    </bs-dialog>
</template>

<script>
import { weekArray } from "@/const/index"
export default {
    name: "PlaySetAttrSlot",
    data() {
        return {
            formData: {},
            resultData: [],
            tableData: [],
            weeks: weekArray,
            brightness: 0,
            start: '',
            end: '',
            weekNames: [],
            indexIds:[],
            rowIndex: 1
        }
    },
    computed:{
        timeSlotArray(){
            return this.getTimeArray(0)
        },
        endTimeSlotArray(){
            let index = this.timeSlotArray.findIndex(item => item.value === this.start)
            console.log('endTimeSlotArray',index)
            index = index > -1?index+1:0
            return this.getTimeArray(index)
        },
        forbidEndTimeSlotArray(){
            let index = this.timeSlotArray.findIndex(item => item.value === this.forbidStart)
            index = index > -1?index+1:0
            return this.getTimeArray(index)
        }
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        initPlayAttrData: {
            type: Array,
            default: () => []
        },
        type: {
            type: String,
            default: 'brightness'
        }
    },
    methods: {
        updateVisible(v) {
            this.$emit('update:visible', v)
        },
        getTimeArray(index){
            var arr = []
            // //小时24等分
            // for(var i= index;i<25;i++){
            //     if(i<10){
            //         arr.push({name:'0'+i+':00',value:'0'+i+':'+"00"})
            //     }else{
            //         arr.push({name:i+':00',value:i+':00'})
            //     }
            // }
            for(var i = index;i<289;i++){
                var hour = parseInt(i/12)
                var minute = parseInt(i/2) % 6
                minute = minute +''+ i%2 * 5
                if(hour < 10){
                    arr.push({name:'0'+hour+':'+minute,value:'0'+hour+':'+minute})
                } else {
                    arr.push({name:hour+':'+minute,value:hour+':'+minute})
                }
            }
            return arr
        },
        doAddWeekInfo() {
            if(this.tableData.length >= 10) {
                this.$message.error('最多只能添加10条时间段')
                return
            }
            if(!this.start) {
                this.$message.error('请选择开始时间')
                return
            }
            if(!this.end) {
                this.$message.error('请选择结束时间')
                return
            }
            const today = this.$dateFormat('Y-m-d', new Date())
            const startTime = new Date(today + ' ' + this.start ).getTime()
            const endTime = new Date(today + ' ' + this.end ).getTime()
            if(startTime >= endTime) {
                this.$message.error('开始时间不能大于结束时间')
                return
            }
            try {
                this.tableData.forEach(item => {
                    let tin = item.timeinfo
                    let st = tin.split('-')[0]
                    let ed = tin.split('-')[1]

                    var stTime = new Date(today + ' ' + st ).getTime()
                    var edTime = new Date(today + ' ' + ed ).getTime()

                    if(startTime < edTime && endTime > stTime){
                        throw Error()
                    }
                })
            } catch (e) {
                this.$message.error('添加的时间段与已存在的时间段冲突')
                return
            }
            let timeinfo = this.start + '-' + this.end
            let weekinfo =  this.type == 'brightness' ? `亮度${this.brightness}` : `音量:${this.brightness}`
            this.tableData.push({ timeinfo: timeinfo, weekinfo: weekinfo, index: this.rowIndex })
            this.rowIndex = this.rowIndex + 1
            if(!this.resultData){
                this.resultData = []
            }
            this.resultData.push({
                start: this.start,
                end: this.end,
                val: this.brightness,
                week: '1,2,3,4,5,6,7'
            })
        },
        doAddTableData(dataArray) {
            dataArray.forEach(item => {
                let timeinfo = item.start + '-' + item.end
                let weekinfo =  this.type == 'brightness' ? `亮度${item.val}` : `音量:${item.val}`
                this.tableData.push({ timeinfo: timeinfo, weekinfo: weekinfo, index: this.rowIndex  })
                this.rowIndex = this.rowIndex + 1
                this.resultData.push({
                    start: item.start,
                    end: item.end,
                    val: item.val,
                    week: '1,2,3,4,5,6,7'
                })
            })
        },
        getCurrentRow(row, column, event){
            if(this.indexIds.indexOf(row.index) == -1) {
                this.$refs.table.toggleRowSelection(row, true);
            }else{
                this.$refs.table.toggleRowSelection(row, false);
            }
        },
        handleSelectionOnoffsChange(val) {
            this.forbidIndexIds = []
            val.forEach(element => {
                this.forbidIndexIds.push(element.index)
            });
        },
        handleSelectionDownloadsChange(val) {
            this.indexIds = []
            val.forEach(element => {
                this.indexIds.push(element.index)
            });
        },
        // 删除当前行
        deleteRow() {
            if(this.indexIds.length < 1) {
                    this.$alert('提示', '请先选择时间段');
                return
            }
            this.tableData = this.tableData.filter((item)=>{
                return this.indexIds.indexOf(item.index) == -1;
            });
            this.resultData = this.resultData.filter((item,index)=>{
                return this.indexIds.indexOf(index+1) == -1;
            })
            this.indexIds = []
        },
        // 清空表格
        deleteAll() {
            this.tableData = []
            this.resultData = []
            this.rowIndex = 1
        },
        doSave() {
            this.$emit('save', this.resultData, this.type)
            this.doCloseEdit()
        },
        doCloseEdit() {
            this.updateVisible(false)
            this.resultData = []
        },

        initBasicData() {
            this.$nextTick(() => {
                this.tableData = []
                this.start = ''
                this.end = ''
                this.brightness = 0
                this.indexIds = []
                this.rowIndex = 1

                if(this.initPlayAttrData) {
                    this.doAddTableData(this.initPlayAttrData)
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form {
  padding: 15px;
}
::v-deep .el-dialog {
  width: 800px;
  height: 450px;
}
</style>
